<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>链栈</title>
</head>
<body>
    
</body>

<script>


class LinkedStack {
    // 构造方法
    constructor() {
        //定义节点
        class Node {
            constructor(val) {
                this.val = val;
                this.next = null;
            }
        }

        var length = 0; 
        var top;  //栈顶

        // 入栈
        // 入栈的数字作为参数
        this.push = function (val) {
            // 创建新节点,节点元素为输入的数字
            var node = new Node(val);
            // 如果栈为空新节点就是栈顶
            if (!top) {
                top = node;
                length++;
                // 栈顶节点存在元素，就把新元素节点添加在当前
            } else {
                node.next = top;
                top = node;
                length++;
            }
        };
        // 出栈
        // 依据栈的性质，先进后出，所以应该从链表顶部输出
        this.pop = function () {
        // 先获取栈顶，方便下一步更新栈顶
            var current = top;
            // 栈顶不为空
            if (top) {
                // 将栈顶节点后移
                top = current.next;
                length--;
                // 如果全部输出
                if(length==0) {
                    console.log("Stack is empty")
                }
            }
        };
        //打印栈内元素
        this.toString = function () {
            var string = '';
            var current = top;

            while (current) {
                // 将节点元素进行拼接
                string += current.val;
                // 后移，接下一节点元素
                current = current.next;
            }
            console.log(string)
        };
        //清空栈
        this.clear = function () {
            top = null;
            length = 0;
            console.log("Cleared");
        };
    }
}

let stack = new LinkedStack();
stack.push(7);
stack.push(2);
stack.push(4);
stack.push(1)
stack.pop();//去除元素1，达到先入后出
console.log(stack)
stack.toString();
stack.clear();
stack.toString();


</script>
</html>